<template>
  <div>
    <el-dialog
      title="提示"
      :visible.sync="visible"
      width="30%"
      :close-on-click-modal="false"
      :before-close="clickCancel">
      <h3 slot="title">合作记录</h3>
      <div>
        <el-form :model="cooperationForm" :rules="cooperationrules" ref="cooperationFormRefs" label-width="120px">
          <el-form-item v-if="name" label="公司名称" prop="name">
            <el-input v-model="cooperationForm.name" disabled></el-input>
          </el-form-item>
          <!--        <el-form-item label="合同简述" prop="description">
                    <el-input v-model="cooperationForm.description" placeholder="请输入合同内容简述"></el-input>
                  </el-form-item>-->
          <el-form-item label="进款金额（元）" prop="income" >
            <el-input v-model.number="cooperationForm.income" placeholder="请输入进款金额" type="number" @change="checkIncome"></el-input>
          </el-form-item>
          <el-form-item label="进款明细" prop="incomeDetail" >
            <div >
              <el-input class="coo-income-detail" v-if="cooperationForm.incomeDetail" style="margin-bottom: 10px;border: none;" v-model="cooperationForm.incomeDetail" type="textarea" :autosize="{ minRows: 4, maxRows: 6}" placeholder="请填写进款明细" readonly></el-input>
              <el-button @click="showIncomeDetail" type="primary" >编辑</el-button>
            </div>
          </el-form-item>
          <el-form-item label="业绩金额（元）" prop="perfor">
            <el-input v-model.number="cooperationForm.perfor" placeholder="请输入业绩金额" type="number"></el-input>
          </el-form-item>
          <el-form-item v-if="cooperationForm.income > 0" label="进款账号" prop="incomeAccountId" >
            <el-select style="width: 100%" v-model="cooperationForm.incomeAccountId" placeholder="请选择进款账号" @focus="getDictListOptions" @change="changeAccountOption">
              <el-option
                v-for="item in incomeAccountOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="进款时间" prop="incomeDate">
            <el-date-picker type="date"
                            value-format="yyyy-MM-dd"
                            v-model="cooperationForm.incomeDate"
                            placeholder="选择日期"
                            style="width: 100%"></el-date-picker>
          </el-form-item>
          <!--            <el-form-item label="合作明细" >
                        <el-input v-model="cooperationForm.detail" placeholder="请输入明细"></el-input>
                      </el-form-item>-->
          <el-form-item label="消耗金额（元）" prop="consume">
            <el-input v-model.number="cooperationForm.consume"></el-input>
          </el-form-item>
          <el-form-item label="合同文件" prop="">
            <el-upload
              :action="uploadUrl()"
              multiple
              :headers="uploadHeader()"
              :on-success="successUpload"
              :on-change="changeUpload"
              :file-list="cooperationForm.fileList"
              accept=".pdf">
              <el-button type="primary">上传文件</el-button>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
    <el-button @click="clickCancel">取 消</el-button>
    <el-button type="primary" @click="clickUpdate">确 定</el-button>
  </span>
    </el-dialog>
    <income-detail ref="incomeDetailRefs" :dialog-visible="incomeDetailDialogVisible" @dialogVisibleChange="changeIncomeDetailDialogVisible" @getIncomeDetailData="setIncomeDetailData"></income-detail>
  </div>


</template>

<script>
import Vue from 'vue'
import {addCooperation} from '../../../../api/customer/regionalList'
import {incomeType} from '../../../../api/customer/enterprise'
import IncomeDetail from './IncomeDetail'
import {getDictList} from '../../../../api/customer/commom'

export default {
  name: 'AddCooperationDialog',
  components: {IncomeDetail},
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    },
    id: {
      type: [Number, String],
      default: null
    },
    name: {
      type: String,
      default: ''
    }
  },
  created () {
    this.setForm()
  },
  data () {
    let consumeValidater = (rule, value, callback) => {
      const income = this.cooperationForm.income
      if (Math.abs(value) > Math.abs(income)) {
        callback(new Error('消耗金额不得大于进款金额！'))
      } else {
        callback()
      }
    }
    let incomeValidater = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入进款金额'))
      } else if (Number(value) !== Number(this.sum)) {
        callback(new Error('输入的进款金额与明细中的不同，请检查！'))
      } else {
        callback()
      }
    }
    return {
      typeOptions: [],
      incomeAccountOptions: [],
      visible: this.dialogVisible,
      incomeDetailDialogVisible: false,
      // 小计总额
      subtotal: '',
      // 进款总额
      sum: '',
      cooperationForm: {
        'name': this.name,
        'customerId': this.id,
        'description': '',
        'income': '',
        'incomeDate': '',
        'perfor': '',
        // 'typeId': 1,
        'fileName': '',
        'fileUrl': '',
        'fileList': [],
        // 对应提交表单的detail
        'incomeDetail': '',
        'incomeAccountId': '',
        'incomeDetailList': '',
        'incomeAccount': '',
        'consume': 0
      },
      cooperationrules: {
        description: [{ required: true, message: '请输入合同简介', trigger: 'blur' }],
        income: [{ required: true, validator: incomeValidater, trigger: 'change' }],
        incomeDate: [{ required: true, message: '请选择进款时间', trigger: 'change' }],
        perfor: [{ required: true, message: '请输入业绩金额', trigger: 'blur' }],
        // typeId: [{ required: true, message: '请选择类型', trigger: 'change' }],
        incomeDetail: [{ required: true, message: '请填写进款明细', trigger: 'blur' }],
        incomeAccountId: [{ required: true, message: '请选择进款账号', trigger: 'change' }],
        consume: [{validator: consumeValidater, trigger: 'blur'}]
        /*      detail: [{ required: true, message: '请输入合作明细', trigger: 'blur' }] */
      }
    }
  },
  methods: {
    getDictListOptions () {
      // 标识码
      let dataForm = {'dictCode': 'incomeAccount'}
      getDictList(dataForm, ({data}) => {
        this.incomeAccountOptions = data
      })
    },
    gettypeOptions () {
      return incomeType.filter(item => item.id !== 2)
    },
    setForm () {
      this.typeOptions = this.gettypeOptions()
    },
    ininData () {
      Object.keys(this.cooperationForm).forEach(key => {
        this.cooperationForm[key] = ''
      })
      this.cooperationForm.fileList = []
      this.cooperationForm.id = this.id
      this.cooperationForm.name = this.name
      this.$refs.cooperationFormRefs.resetFields()
    },
    clickCancel () {
      // this.$emit('update:addCooperationDialogVisible', false)
     // this.$emit('update:dialogVisible', false)

      this.visible = false
      this.ininData()
      this.$emit('dialogVisibleChange', false)
      this.$refs.cooperationFormRefs.clearValidate()
    },
    // 上传头部
    uploadHeader () {
      return {
        'token': Vue.cookie.get('token')
      }
    },
    uploadUrl () {
      return this.$http.adornUrl('/ent/customer/file/upload')
    },
    // 上传成功监听函数
    successUpload (response, file, fileList) {
      let fileUrl = ''
      if (response.code === 0) {
        let data = response.data
        fileUrl = data.remoteUrl + data.fileName
        this.cooperationForm.fileUrl = fileUrl
        this.cooperationForm.fileName = file.name
      }
    },
    // 文件改变监听函数
    changeUpload (file, fileList) {
      if (fileList.length > 1) {
        fileList.splice(0, 1)
      }
    },
    // 点击上传
    clickUpdate () {
      this.$refs.cooperationFormRefs.validate((valid) => {
        if (valid) {
          if (this.cooperationForm.customerId) {
            let formData = {
              'description': this.cooperationForm.description,
              'income': this.cooperationForm.income,
              'incomeDate': this.cooperationForm.incomeDate,
              'detail': this.cooperationForm.incomeDetail,
              'fileName': this.cooperationForm.fileName,
              'fileUrl': this.cooperationForm.fileUrl,
          // 'typeId': this.cooperationForm.typeId,
              'perfor': this.cooperationForm.perfor,
              'incomeAccount': this.cooperationForm.income > 0 ? this.cooperationForm.incomeAccount : null,
              'incomeAccountId': this.cooperationForm.income > 0 ? this.cooperationForm.incomeAccountId : null,
              'incomeDetailList': this.cooperationForm.incomeDetailList,
              'customerId': this.cooperationForm.customerId,
              'consume': this.cooperationForm.consume || 0
            }
            addCooperation(formData, (data) => {
              this.$message.success('操作成功！')
              this.visible = false
              this.$emit('dialogVisibleChange', false)
              this.$emit('refreshData')
              this.ininData()
              this.$refs.incomeDetailRefs.initData()
            })
          } else {
            this.getCooperationData()
            this.visible = false
            this.$emit('dialogVisibleChange', false)
            this.ininData()
            this.$refs.incomeDetailRefs.initData()
          }
        } else {
          return false
        }
      })
    },
    // 显示进款详情对话框
    showIncomeDetail () {
      this.changeIncomeDetailDialogVisible(true)
    },
    // 设置进款详情对话框显示
    changeIncomeDetailDialogVisible (val) {
      this.incomeDetailDialogVisible = val
    },
    checkIncome () {
      this.$refs.cooperationFormRefs.validateField('income')
    },
    setIncomeDetailData (data) {
      let detailText = ''
      let incomeDetailList = []
      if (data) {
        const {textList, tableData, subtotal, sum} = data
        textList.forEach((item) => {
          if (item.content) {
            detailText += `${item.content}\n`
          }
        })
        detailText = `明细 进款总额:${sum}\n\n` + detailText
        tableData.forEach((item) => {
          let incomeDetailItem = {}
          incomeDetailItem['typeId'] = item.typeId
          incomeDetailItem['subjectId'] = item.projectId
          incomeDetailItem['explain'] = item.explain
          incomeDetailItem['unitPrice'] = item.perPrice
          incomeDetailItem['amount'] = item.num
          incomeDetailItem['subtotal'] = item.perPrice * item.num
          incomeDetailItem['tax'] = item.tax
          incomeDetailList.push(incomeDetailItem)
        })
        this.cooperationForm.incomeDetail = detailText
        // subtotal为总计等于进款金额
        this.subtotal = subtotal
        this.sum = sum
        // 局部验证income字段是否等于明细的进款字段
        this.$refs.cooperationFormRefs.validateField('income')
        this.cooperationForm.incomeDetailList = incomeDetailList
      }
    },
    getCooperationData () {
      this.$emit('getCooperationData', this.cooperationForm)
    },
    changeAccountOption (option) {
      // console.log('option', option)

      this.cooperationForm.incomeAccount = this.incomeAccountOptions.filter(item => item.id === option)[0].name
      // console.log('incomeAccount', this.cooperationForm.incomeAccount)
    }
  },
  watch: {
    dialogVisible (val) {
      this.visible = val
    },
    id (val) {
      this.cooperationForm.customerId = val
    },
    name (val) {
      this.cooperationForm.name = val
    }
  }
}
</script>

<style lang="less" >
.coo-income-detail{
    .el-textarea__inner{
      border: none !important;
    }


}
</style>
